<template>
  <div class="visit-assistant">
    <div class="chat-container">
      <!-- 对话历史区域 -->
      <div class="chat-history" ref="chatHistoryRef">
        <div
          v-for="message in messages"
          :key="message.id"
          :class="['message-item', message.type]"
        >
          <div class="message-avatar">
            {{ message.type === "assistant" ? "助" : "我" }}
          </div>
          <div class="message-content">
            <div class="message-text">
              <div v-html="formatMessageContent(message.content)"></div>
            </div>
            <div class="message-time">{{ message.timestamp }}</div>
          </div>
        </div>
      </div>

      <!-- 输入区域 -->
      <div class="input-area">
        <div class="voice-input-container">
          <el-button
            v-if="!isRecording"
            @click="toggleVoiceInput"
            type="primary"
            icon="el-icon-microphone"
          >
            语音输入
          </el-button>
          <el-button
            v-else
            @click="stopVoiceRecording"
            type="danger"
            icon="el-icon-microphone"
          >
            停止录音
          </el-button>
        </div>
        <el-input
          v-model="inputContent"
          placeholder="请输入您的问题或需求..."
          :rows="3"
          type="textarea"
          @keydown.enter.native.prevent="sendMessage"
          style="resize: none"
        ></el-input>
        <div class="send-container">
          <div class="shortcut-responses">
            <el-button
              v-for="shortcut in shortcutResponses"
              :key="shortcut.id"
              type="text"
              @click="useShortcutResponse(shortcut.content)"
            >
              {{ shortcut.content }}
            </el-button>
          </div>
          <el-button
            type="primary"
            @click="sendMessage"
            :disabled="!inputContent.trim()"
          >
            发送
          </el-button>
        </div>
      </div>
    </div>

    <!-- 常用工具区域 -->
    <div class="tools-area">
      <h4 class="tools-title">常用工具</h4>
      <div class="tool-buttons">
        <el-button
          type="info"
          icon="el-icon-document"
          @click="openCheckBillModal"
        >
          查账单
        </el-button>
        <el-button
          type="info"
          icon="el-icon-shopping-cart"
          @click="openCheckPackageModal"
        >
          查套餐信息
        </el-button>
        <el-button
          type="info"
          icon="el-icon-tickets"
          @click="openCheckWorkOrderModal"
        >
          查服务工单
        </el-button>
      </div>
    </div>

    <!-- 查账单弹窗 -->
    <el-dialog title="查询客户账单" v-model="showBillModal" width="600px">
      <el-form :model="billForm" label-width="100px">
        <el-form-item label="客户姓名">
          <el-input
            v-model="billForm.customerName"
            placeholder="请输入客户姓名"
          ></el-input>
        </el-form-item>
        <el-form-item label="查询周期">
          <el-date-picker
            v-model="billForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            style="width: 100%"
          ></el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="checkBill">查询</el-button>
          <el-button @click="showBillModal = false">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

    <!-- 查套餐信息弹窗 -->
    <el-dialog
      title="查询客户套餐信息"
      v-model="showPackageModal"
      width="600px"
    >
      <el-form :model="packageForm" label-width="100px">
        <el-form-item label="客户姓名">
          <el-input
            v-model="packageForm.customerName"
            placeholder="请输入客户姓名"
          ></el-input>
        </el-form-item>
        <el-form-item label="手机号码">
          <el-input
            v-model="packageForm.phoneNumber"
            placeholder="请输入手机号码"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="checkPackage">查询</el-button>
          <el-button @click="showPackageModal = false">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

    <!-- 查服务工单弹窗 -->
    <el-dialog title="查询服务工单" v-model="showWorkOrderModal" width="800px">
      <el-form :model="workOrderForm" label-width="100px">
        <el-form-item label="客户姓名">
          <el-input
            v-model="workOrderForm.customerName"
            placeholder="请输入客户姓名"
          ></el-input>
        </el-form-item>
        <el-form-item label="工单号">
          <el-input
            v-model="workOrderForm.orderNumber"
            placeholder="请输入工单号（选填）"
          ></el-input>
        </el-form-item>
        <el-form-item label="工单状态">
          <el-select
            v-model="workOrderForm.status"
            placeholder="请选择工单状态（选填）"
          >
            <el-option label="全部" value=""></el-option>
            <el-option label="待处理" value="pending"></el-option>
            <el-option label="处理中" value="processing"></el-option>
            <el-option label="已完成" value="completed"></el-option>
            <el-option label="已取消" value="cancelled"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="checkWorkOrder">查询</el-button>
          <el-button @click="showWorkOrderModal = false">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

    <!-- 使用说明弹窗 -->
    <el-dialog title="走访助手使用说明" v-model="showHelpModal" width="700px">
      <div class="help-content">
        <h4>如何使用走访助手？</h4>
        <ol>
          <li>在输入框中输入您的问题或需求，点击发送按钮</li>
          <li>使用语音输入功能，点击麦克风按钮开始录音，再次点击结束录音</li>
          <li>选择快捷回复，快速发送常用问题</li>
          <li>使用常用工具，查询客户账单、套餐信息和服务工单</li>
        </ol>
        <h4>适用场景：</h4>
        <ul>
          <li>在走访过程中快速获取客户相关信息</li>
          <li>记录走访要点和客户反馈</li>
          <li>获取产品信息和销售建议</li>
          <li>生成走访报告草稿</li>
        </ul>
        <h4>语音输入提示：</h4>
        <ul>
          <li>请确保您的设备麦克风正常工作</li>
          <li>在相对安静的环境中使用语音输入</li>
          <li>使用普通话，语速适中</li>
        </ul>
      </div>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, nextTick } from "vue";
import { ElMessage } from "element-plus";
// import { useRouter } from "vue-router";

// 类型定义
interface Message {
  id: string;
  type: "user" | "assistant";
  content: string;
  timestamp: string;
}

interface ShortcutResponse {
  id: string;
  content: string;
}

interface BillForm {
  customerName: string;
  dateRange: [string, string] | null;
}

interface PackageForm {
  customerName: string;
  phoneNumber: string;
}

interface WorkOrderForm {
  customerName: string;
  orderNumber: string;
  status: string;
}

// 状态管理
// const router = useRouter()

// 对话历史引用
const chatHistoryRef = ref<HTMLElement | null>(null);

// 对话消息数组
const messages = ref<Message[]>([
  {
    id: "1",
    type: "assistant",
    content:
      "您好！我是您的走访助手，请问有什么可以帮助您的吗？您可以：\n1. 输入问题获取帮助\n2. 使用语音输入功能\n3. 点击快捷回复\n4. 使用常用工具查询信息",
    timestamp: "10:00",
  },
]);

// 输入框内容
const inputContent = ref("");

// 快捷回复选项
const shortcutResponses = ref<ShortcutResponse[]>([
  {
    id: "s1",
    content: "客户对当前套餐有什么意见？",
  },
  {
    id: "s2",
    content: "如何向客户推荐新套餐？",
  },
  {
    id: "s3",
    content: "客户的账单情况如何？",
  },
  {
    id: "s4",
    content: "客户有哪些未解决的工单？",
  },
]);

// 语音输入相关
const isRecording = ref(false);
const recordingStartTime = ref<number>(0);

// 弹窗控制
const showBillModal = ref(false);
const showPackageModal = ref(false);
const showWorkOrderModal = ref(false);
const showHelpModal = ref(false);

// 表单数据
const billForm = reactive<BillForm>({
  customerName: "",
  dateRange: null,
});

const packageForm = reactive<PackageForm>({
  customerName: "",
  phoneNumber: "",
});

const workOrderForm = reactive<WorkOrderForm>({
  customerName: "",
  orderNumber: "",
  status: "",
});

// 格式化消息内容，将换行符转换为<br>
const formatMessageContent = (content: string): string => {
  return content.replace(/\n/g, "<br>");
};

// 滚动到最新消息
const scrollToLatestMessage = () => {
  nextTick(() => {
    if (chatHistoryRef.value) {
      chatHistoryRef.value.scrollTop = chatHistoryRef.value.scrollHeight;
    }
  });
};

// 发送消息
const sendMessage = () => {
  const content = inputContent.value.trim();
  if (!content) {
    ElMessage.warning("请输入消息内容");
    return;
  }

  // 添加用户消息
  const userMessage: Message = {
    id: Date.now().toString(),
    type: "user",
    content,
    timestamp: new Date().toLocaleTimeString([], {
      hour: "2-digit",
      minute: "2-digit",
    }),
  };
  messages.value.push(userMessage);
  inputContent.value = "";
  scrollToLatestMessage();

  // 根据用户输入生成助手回复
  setTimeout(() => {
    generateAssistantResponse(content);
  }, 1000);
};

// 生成助手回复
const generateAssistantResponse = (userInput: string) => {
  let response = "";

  // 根据关键词生成不同的回复
  if (userInput.includes("账单")) {
    response = `您可以使用左侧的"查账单"工具来查询客户账单信息。\n1. 点击"查账单"按钮\n2. 输入客户姓名和查询周期\n3. 点击查询按钮获取账单详情`;
  } else if (userInput.includes("套餐")) {
    response = `您可以使用左侧的"查套餐信息"工具来查询客户套餐。\n1. 点击"查套餐信息"按钮\n2. 输入客户姓名和手机号码\n3. 点击查询按钮获取套餐详情`;
  } else if (userInput.includes("工单")) {
    response = `您可以使用左侧的"查服务工单"工具来查询客户服务工单。\n1. 点击"查服务工单"按钮\n2. 输入客户姓名和工单号（可选）\n3. 选择工单状态（可选）\n4. 点击查询按钮获取工单列表`;
  } else if (userInput.includes("帮助") || userInput.includes("使用说明")) {
    response =
      "点击右上角的帮助按钮可以查看详细的使用说明。\n\n您也可以使用以下功能：\n• 文本输入：输入您的问题并发送\n• 语音输入：点击麦克风按钮进行语音输入\n• 快捷回复：选择常用问题快速发送\n• 常用工具：查询账单、套餐和工单信息";
  } else if (userInput.includes("总结")) {
    response =
      "您可以让我帮您总结本次走访的要点。请告诉我：\n1. 客户的主要需求和反馈\n2. 讨论的关键问题\n3. 达成的共识或下一步计划" +
      '\n\n<el-button type="text" style="color: #409eff;" @click="generateSummary">生成走访总结</el-button>';
  } else {
    response = `感谢您的提问！\n\n针对您的问题："${userInput}"\n\n1. 您可以尝试使用左侧的相关工具获取信息\n2. 也可以提供更多细节，以便我能更准确地帮助您\n3. 或者点击右上角的帮助按钮查看使用说明`;
  }

  // 添加助手回复
  const assistantMessage: Message = {
    id: (Date.now() + 1).toString(),
    type: "assistant",
    content: response,
    timestamp: new Date().toLocaleTimeString([], {
      hour: "2-digit",
      minute: "2-digit",
    }),
  };
  messages.value.push(assistantMessage);
  scrollToLatestMessage();
};

// 使用快捷回复
const useShortcutResponse = (content: string) => {
  inputContent.value = content;
};

// 切换语音输入
const toggleVoiceInput = () => {
  if (!("webkitSpeechRecognition" in window || "SpeechRecognition" in window)) {
    ElMessage.error("您的浏览器不支持语音识别功能，请尝试使用Chrome浏览器");
    return;
  }

  isRecording.value = true;
  recordingStartTime.value = Date.now();
  ElMessage.success("开始录音，请说话...");

  // 模拟语音识别
  setTimeout(() => {
    stopVoiceRecording();
    // 模拟识别结果
    const mockResult = "客户对企业云通信平台表示兴趣，希望了解更多详情和报价。";
    inputContent.value = mockResult;
    ElMessage.success("语音识别完成");
  }, 3000);
};

// 停止录音
const stopVoiceRecording = () => {
  isRecording.value = false;
  const recordingTime = Math.floor(
    (Date.now() - recordingStartTime.value) / 1000
  );
  ElMessage.info(`录音已停止，时长：${recordingTime}秒`);
};

// 打开查账单弹窗
const openCheckBillModal = () => {
  showBillModal.value = true;
};

// 查询账单
const checkBill = async () => {
  if (!billForm.customerName) {
    ElMessage.error("请输入客户姓名");
    return;
  }

  if (!billForm.dateRange) {
    ElMessage.error("请选择查询周期");
    return;
  }

  try {
    // 模拟API调用
    await new Promise((resolve) => setTimeout(resolve, 1000));

    // 模拟查询结果
    const billInfo = `客户：${billForm.customerName}\n查询周期：${billForm.dateRange[0]} 至 ${billForm.dateRange[1]}\n本月账单：¥1,280.00\n已支付金额：¥0.00\n未支付金额：¥1,280.00\n支付状态：待支付\n到期日：2023-07-25`;

    // 添加到对话历史
    const billMessage: Message = {
      id: Date.now().toString(),
      type: "assistant",
      content: billInfo,
      timestamp: new Date().toLocaleTimeString([], {
        hour: "2-digit",
        minute: "2-digit",
      }),
    };
    messages.value.push(billMessage);
    scrollToLatestMessage();

    showBillModal.value = false;
    ElMessage.success("账单查询成功");
  } catch (error) {
    ElMessage.error("查询失败，请重试");
    console.error("查询账单失败:", error);
  }
};

// 打开查套餐信息弹窗
const openCheckPackageModal = () => {
  showPackageModal.value = true;
};

// 查询套餐信息
const checkPackage = async () => {
  if (!packageForm.customerName) {
    ElMessage.error("请输入客户姓名");
    return;
  }

  if (!packageForm.phoneNumber) {
    ElMessage.error("请输入手机号码");
    return;
  }

  try {
    // 模拟API调用
    await new Promise((resolve) => setTimeout(resolve, 1000));

    // 模拟查询结果
    const packageInfo = `客户：${packageForm.customerName}\n手机号码：${packageForm.phoneNumber}\n当前套餐：企业精英套餐\n套餐月费：¥880.00\n包含内容：\n• 500M光纤宽带\n• 500分钟国内通话\n• 100G企业云盘\n• 10个企业邮箱\n套餐到期日：2023-12-31`;

    // 添加到对话历史
    const packageMessage: Message = {
      id: Date.now().toString(),
      type: "assistant",
      content: packageInfo,
      timestamp: new Date().toLocaleTimeString([], {
        hour: "2-digit",
        minute: "2-digit",
      }),
    };
    messages.value.push(packageMessage);
    scrollToLatestMessage();

    showPackageModal.value = false;
    ElMessage.success("套餐信息查询成功");
  } catch (error) {
    ElMessage.error("查询失败，请重试");
    console.error("查询套餐信息失败:", error);
  }
};

// 打开查服务工单弹窗
const openCheckWorkOrderModal = () => {
  showWorkOrderModal.value = true;
};

// 查询服务工单
const checkWorkOrder = async () => {
  if (!workOrderForm.customerName) {
    ElMessage.error("请输入客户姓名");
    return;
  }

  try {
    // 模拟API调用
    await new Promise((resolve) => setTimeout(resolve, 1000));

    // 模拟查询结果
    const workOrderInfo = `客户：${workOrderForm.customerName}\n工单号：WO20230701001\n工单类型：网络故障\n提交时间：2023-07-01 14:30\n处理状态：处理中\n预计完成时间：2023-07-02 12:00\n故障描述：办公室网络连接不稳定，部分设备无法正常上网\n处理进度：技术人员已上门检测，正在排查故障原因`;

    // 添加到对话历史
    const workOrderMessage: Message = {
      id: Date.now().toString(),
      type: "assistant",
      content: workOrderInfo,
      timestamp: new Date().toLocaleTimeString([], {
        hour: "2-digit",
        minute: "2-digit",
      }),
    };
    messages.value.push(workOrderMessage);
    scrollToLatestMessage();

    showWorkOrderModal.value = false;
    ElMessage.success("工单查询成功");
  } catch (error) {
    ElMessage.error("查询失败，请重试");
    console.error("查询工单失败:", error);
  }
};

// 生成走访总结
// const generateSummary = () => {
//   // 构建总结内容
//   const summary =
//     "走访总结草稿\n\n日期：2023-07-10\n客户：ABC贸易有限公司\n\n主要讨论内容：\n1. 客户对企业云通信平台表示兴趣，希望提供详细方案和报价\n2. 客户反映当前网络稳定性存在问题，希望尽快解决\n3. 讨论了企业精英套餐的升级方案\n\n客户需求：\n1. 稳定可靠的网络连接\n2. 高效的企业通信解决方案\n3. 优惠的套餐价格\n\n下一步计划：\n1. 提交企业云通信平台详细方案和报价\n2. 安排技术人员上门排查网络问题\n3. 提供套餐升级建议\n\n建议：优先解决网络问题，提升客户满意度后再进行产品推广";

//   // 添加到对话历史
//   const summaryMessage: Message = {
//     id: Date.now().toString(),
//     type: "assistant",
//     content:
//       summary +
//       '\n\n<el-button type="text" style="color: #409eff;" @click="confirmSummary">确认使用此总结</el-button>',
//     timestamp: new Date().toLocaleTimeString([], {
//       hour: "2-digit",
//       minute: "2-digit",
//     }),
//   };
//   messages.value.push(summaryMessage);
//   scrollToLatestMessage();
// };

// 确认使用总结
// const confirmSummary = () => {
//   // 发送总结到父组件
//   const summary =
//     messages.value.find((msg) => msg.content.includes("走访总结草稿"))
//       ?.content || "";
//   if (summary) {
//     // 这里应该通过事件发送到父组件
//     console.log("总结已确认:", summary);
//     ElMessage.success("走访总结已确认");
//   }
// };

// 组件挂载时滚动到底部
onMounted(() => {
  scrollToLatestMessage();
});
</script>

<style lang="scss" scoped>
.visit-assistant {
  display: flex;
  height: 100vh;
  background-color: #f5f7fa;
  
  /* 聊天容器 */
  .chat-container {
    flex: 1;
    display: flex;
    flex-direction: column;
    margin-right: 20px;
    padding: 20px;
    background-color: white;
    border-radius: 8px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
    position: relative;
    
    /* 对话历史区域 */
    .chat-history {
      flex: 1;
      overflow-y: auto;
      padding: 10px;
      margin-bottom: 20px;
      
      /* 消息项 */
      .message-item {
        display: flex;
        margin-bottom: 20px;
        animation: fadeIn 0.3s ease-in;
        
        &.user {
          flex-direction: row-reverse;
          
          .message-avatar {
            background-color: #67c23a;
          }
          
          .message-content {
            text-align: right;
            
            .message-text {
              background-color: #409eff;
              color: white;
            }
          }
        }
        
        /* 消息头像 */
        .message-avatar {
          width: 36px;
          height: 36px;
          border-radius: 50%;
          background-color: #409eff;
          color: white;
          display: flex;
          align-items: center;
          justify-content: center;
          font-size: 14px;
          font-weight: bold;
          margin: 0 10px;
          flex-shrink: 0;
        }
        
        /* 消息内容 */
        .message-content {
          max-width: 70%;
          
          /* 消息文本 */
          .message-text {
            background-color: #f0f4f8;
            padding: 10px 15px;
            border-radius: 8px;
            word-wrap: break-word;
            line-height: 1.6;
          }
          
          /* 消息时间 */
          .message-time {
            font-size: 12px;
            color: #909399;
            margin-top: 5px;
          }
        }
      }
    }
    
    /* 输入区域 */
    .input-area {
      border-top: 1px solid #e4e7ed;
      padding-top: 20px;
      
      /* 语音输入容器 */
      .voice-input-container {
        margin-bottom: 10px;
      }
      
      /* 发送容器 */
      .send-container {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-top: 10px;
        
        /* 快捷回复 */
        .shortcut-responses {
          display: flex;
          gap: 10px;
          flex-wrap: wrap;
        }
      }
    }
  }
  
  /* 工具区域 */
  .tools-area {
    width: 300px;
    padding: 20px;
    background-color: white;
    border-radius: 8px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
    
    /* 工具标题 */
    .tools-title {
      margin-bottom: 20px;
      color: #303133;
      font-size: 16px;
      font-weight: bold;
    }
    
    /* 工具按钮 */
    .tool-buttons {
      display: flex;
      flex-direction: column;
      gap: 15px;
    }
    
    /* 帮助内容 */
    .help-content {
      font-size: 14px;
      line-height: 1.8;
      
      h4 {
        margin: 15px 0 10px 0;
        color: #303133;
      }
      
      ol,
      ul {
        margin: 10px 0;
        padding-left: 20px;
        
        li {
          margin-bottom: 5px;
          color: #606266;
        }
      }
    }
  }
}

@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

/* 响应式布局 */
@media (max-width: 1024px) {
  .visit-assistant {
    flex-direction: column;
    
    .chat-container {
      margin-right: 0;
      margin-bottom: 20px;
    }
    
    .tools-area {
      width: 100%;
      margin-bottom: 20px;
      
      .tool-buttons {
        flex-direction: row;
        justify-content: space-between;
      }
    }
  }
}

@media (max-width: 768px) {
  .visit-assistant {
    padding: 10px;
    
    .chat-container {
      padding: 15px;
    }
    
    .tools-area {
      padding: 15px;
      
      .tool-buttons {
        flex-direction: column;
      }
    }
    
    .message-content {
      max-width: 85%;
    }
  }
}
</style>
